package com.suptracking.web.servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.suptracking.crypt.BCrypt;
import com.suptracking.entity.User;
import com.suptracking.dao.UserDao;
import com.suptracking.service.UserService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(name = "LoginServlet", urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	
	@EJB
	private UserService userservice;
   
	
   
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req,resp);
	}



	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String pseudo = request.getParameter("pseudo");
		String password = request.getParameter("password");
		
		User userfind = userservice.getUserByName(pseudo);
		boolean err = false;
if(userfind!=null){
			
			if(BCrypt.checkpw(password, userfind.getPassword())){
				
				
				HttpSession session = request.getSession();
				session.setAttribute("User", userfind);
				session.setAttribute("UserSession", userfind.getFirstName());
				session.setAttribute("AccType", userfind.isAccType());
				
				//response.sendRedirect(request.getServletContext().getContextPath()+"/GetUserInfo?id="+userfind.getId());
				response.sendRedirect(request.getServletContext().getContextPath()+"/index");
				
				
			}
			
			else {
				
				request.setAttribute("errorPassword", false);
				err = true;
				
				
			}
			
			
		}
		
		else {
			err = true;
			request.setAttribute("errorLogin", false);
			
		}
		if (err){
			response.sendRedirect(request.getServletContext().getContextPath()+"/login.jsp");
		//request.getRequestDispatcher("/Login.jsp").forward(request, response);
		}
		
	}

	

}
